import { request } from "../../request/index";

Page({
  data:{
    tabs:[
      {
        id:0,
        value:"全部",
        isActive:true
      },
      {
        id:1,
        value:"待付款",
        isActive:false
      },
      {
        id:2,
        value:"待收货",
        isActive:false
      },
      {
        id:3,
        value:"退款/退货",
        isActive:false
      }],
    orders:[]
  },

  onShow(){
    const token=wx.getStorageSync('token');
    if(!token){
      wx.navigateTo({
        url: '/pages/auth/index',
      })
    }

    // 1 获取页面数据 type
    let pages=getCurrentPages();
    // 当前页面
    let CurrentPages=pages[pages.length-1];
    const {type}=CurrentPages.options;
    // 2 激活页面
    this.ChangeTitleByIndex(type-1);
    // 3 发送请求
    this.getOrders(type);
  },
    
  // 请求订单数据
  async getOrders(type){
    const res=await request({url:"/my/orders/all",data:{type}});
    this.setData({
      orders:res.orders.map(v=>({...v,create_time_cn:(new Date(v.create_time*1000).toLocaleString())}))
    })
  },

  // 标题点击事件 从子组件传递过来
  handleTabsItemChange(e){
    // 获取索引
    const {index}=e.detail;
    this.ChangeTitleByIndex(index);    
    // 重新发送请求
    this.getOrders(index+1);
  },

  ChangeTitleByIndex(index){
    // 修改原数组
    let {tabs}=this.data;
    tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);
    // 赋值到data
    this.setData({tabs})
  }

})